<?php
/**
******商品管理:添加、修改、删除
**/
class GoodsAction extends Action{
	public function preMethod()
	{
		R("Mayijie/check_admin");
		$perm_key = session('admin_perm');
		$perm_arr = explode(",",$perm_key);
		if(!in_array(4,$perm_arr)){
			$this->error("无权操作");
		}
	}

	public function top(){
		$this->display();
	}

	public function index(){
		$this->cat=R('Goodscat/get_cat');        //获取商品分类列表	
		$this->display();
	}
	public function menu(){
		$this->display();
	}
   //添加商品编辑页面
	public function add_goods(){
		$ShopModel = new WeishopModel();
		$this->shop_list       = $ShopModel->getShopListAll();
		$this->goods_cat     =R('Goodscat/get_cat');        //获取商品分类列表	
		$this->goods_brand =R('Goodsbrand/get_brand');//获取商品品牌列表
		$this->goods_place =R('Goodsplace/get_list');     //获取货位列表
		$this->goods_prop   =R('Goodsprop/get_prop');    //获取规格列表
		$this->goods_label   =R('Goodslabel/get_label');   //获取规格列表
		$this->display();
	}
    
	//检查货号是否重复
	public function check_bn(){
		$Goods_bn=M('Goods');
		$map['bn']=$this->_get("goods_bn");
		$ck=$Goods_bn->where($map)->select();
		if($ck){echo '<font color="#FF0000" size="2">此编号已经被占用!</font>';}
	}
	/**
	********商品添加*start*
	**/
	public function add(){
		$Goods     = M('Goods');
		$Products = M('Products');
		
		//获取基本信息
		$data['cat_id']             =$this->_post('goods_cat');        //商品分类
		$data['shop_id']         = $this->_post('shop_id');
		$data['goods_name']  =$this->_post('goods_name');     //商品名称
		$data['goods_brand']  =$this->_post('goods_brand');    //品牌
		$bn                             =$this->_post('goods_bn');         //货号
		$data['unit']                 =$this->_post('goods_unit');       //单位
        $data['s_intro']            =$this->_post('s_intro');              //简介
	    $data['is_post']           =$this->_post('is_post');             //是否上架
	    $data['price']               =$this->_post('goods_price');     //价格
		$data['cost']                =$this->_post('goods_cost');      //成本
		$data['market_price']   =$this->_post('mktprice');           //市场价
		$data['weight']             =$this->_post('goods_weight');  //重量
		$data['store_place']    =$this->_post('goods_place');   //货位
		$data['intro']               =stripslashes($_POST['content']);          //详细介绍
		$data['goods_label']   =$this->_post('goods_label');
		$store                        =$this->_post('goods_store');
		if(empty($bn)){
			$data['bn']="G".date("md").rand(10000,99999);
		}else{
			$data['bn']=$bn;
		}
		if(empty($data['goods_name'])){
			$this->error("商品名称不得为空！");
		}
        
		/*
		if(!empty($goods_label)){
		     $data['goods_label']   =implode(",",$goods_label);  //标签
		}
		*/
		$data['uptime']           =time();
		$data['last_motify']    =time();

		//获取规格差别价格
		$prop_price=$this->_post('prop_price');
		$prop_store=$this->_post('prop_store');

		//获取扩展属性
		$kz_name =   $this->_post('kz_name');   //获取扩展属性名 @数组 与扩展值对应，注意：如果扩展值为空则丢弃
		$kuozhan  =   $this->_post('kuozhan');   //获取扩展属性值  @数组
		$kuozhan_id=$this->_post('value_id');
		for($i=0;$i<count($kuozhan);$i++){
			if(!empty($kuozhan[$i])){
				$goods_kz[]=array('pdt'=>$kuozhan_id[$i],'kz_name'=>$kz_name[$i],'kuozhan'=>$kuozhan[$i]); //%处理得到数据库数据
			}
		}
				
        //获取规格名
		$prop_name     =$this->_post('prop_name');  //获取规格名    @数组
		$prop1     =    $this->_post('prop1');           //获取规格值1  @数组
		$prop2     =    $this->_post('prop2');           //获取规格值2  @数组

		//如果基本信息库存没有输入，则将差别库存加总
		if(empty($store)){
			$sto=0;
			for($i=0;$i<count($prop1);$i++){
				$sto+=$prop_store[$i];
			}
			$data['store']=$sto;
		}else{
			$data['store']=$store;    //库存
		}
        
		//过滤相同的规格值
		foreach($prop1 as $v1){if(!in_array($v1,$n_prop1)&&!empty($v1)) $n_prop1[]=$v1;}
		foreach($prop2 as $v2){if(!in_array($v2,$n_prop2)&&!empty($v2)) $n_prop2[]=$v2;}
		//将所有的规格转为数组，存入e_goods:props字段
		$prop_num=count($prop_name);
		switch($prop_num){
			case 1:$prop[]=array('prop_name'=>$prop_name[0],'prop_value'=>$n_prop1);break;
			case 2:$prop[]=array('prop_name'=>$prop_name[0],'prop_value'=>$n_prop1);
			            $prop[]=array('prop_name'=>$prop_name[1],'prop_value'=>$n_prop2);break;
		}
		//%处理得到数据库数据
		if(!empty($prop1)){$data['props']=json_encode($prop);}//规格
		if(!empty($kuozhan)){$data['pdt']=serialize($goods_kz);}//扩展属性

		//@开始上传到goods
		$good_id=$Goods->add($data);
		if($good_id==false){
			$this->error("添加商品失败！");
		}

		$data2['goods_id']       =$good_id;
		$data2['cost']              =$this->_post('goods_cost');
		$data2['market_price'] =$this->_post('mktprice');
		$data2['weight']           =$this->_post('goods_weight');
		$data2['name']            =$this->_post('goods_name'); 
		$data2['uptime']           =time();
		$data2['last_modify']   =time();
         
		if(count($prop1)==0){
			$data2['bn']=$data['bn']; 
			$data2['price']=$this->_post('goods_price');
			$data2['store']=$this->_post('goods_store'); 
			//添加到products
			$pd_result=$Products->add($data2);
		}else{
			$bn=$data['bn'];
			$store=$this->_post('goods_store');
			for($i=0;$i<count($prop1);$i++){
				//为空则忽略
			   if(!empty($prop1[$i])){
				    $num=$i+1;
					$data2['bn']=$bn."-".$num;
					if(empty($prop_price[$i])){
						$data2['price']=$this->_post('goods_price');
					}else{
						$data2['price']=$prop_price[$i];
					}
					if(empty($prop_store[$i])){
						$data2['store']=$store/count($prop1);
					}else{
						$data2['store']=$prop_store[$i]; 
					}
					if(!empty($prop2)){
					     $data2['props']=$prop1[$i].",".$prop2[$i];
					}else{
						$data2['props']=$prop1[$i];
					}

					$pd_result=$Products->add($data2);
					}
			//if-end
			   }
		}
		//图片上传，批量，第一张为封面，返回名统一，没有加前缀：（大中小）b_,m_,s_
		    $pic=R("Goodspic/upload");
			if(!empty($pic)){
			    $Goods->s_pic=$pic[0]['savepath']."s_".$pic[0]['savename'];
			    $Goods->m_pic=$pic[0]['savepath']."m_".$pic[0]['savename'];
			    //$Goods->b_pic=$pic[0]['savepath']."b_".$pic[0]['savename'];
			    $map['goods_id']=$good_id;
			    $picresult=$Goods->where($map)->save();
			}

			$Picmm=M("Goods_pic");
            
			for($j=0;$j<count($pic);$j++){
				$data3['goods_id']=$data2['goods_id'];
				$data3['s_pic']=$pic[$j]['savepath']."s_".$pic[$j]['savename'];
				$data3['m_pic']=$pic[$j]['savepath']."m_".$pic[$j]['savename'];
				$data3['b_pic']=$pic[$j]['savepath']."b_".$pic[$j]['savename'];
				$Picmm->add($data3);
			}

			if($good_id&&$pd_result){
				$this->success("商品添加成功！");
			}else{
				$this->error("添加失败！");
			}
	}
	/***商品添加end***/

	//更新商品
	public function edit(){
		$ShopModel = new WeishopModel();
		$this->shop_list       = $ShopModel->getShopListAll();
		$this->goods_cat     =R('Goodscat/get_cat');        //获取商品分类列表	
		$this->goods_brand =R('Goodsbrand/get_brand');//获取商品品牌列表
		$this->goods_place =R('Goodsplace/get_list');     //获取货位列表
		$this->goods_prop   =R('Goodsprop/get_prop');    //获取规格列表
		$this->goods_label   =R('Goodslabel/get_label');   //获取规格列表

		$id=$this->_get('id');
		$Goods=M('Goods');
		$Product=M('Products');
		$Pic=M('Goods_pic');
		$map['goods_id']=$id;

		$goods=$Goods->where($map)->find();
		$product=$Product->where($map)->select();
		$this->pic=$Pic->where($map)->select();

		for($i=0;$i<count($product);$i++){
			$prop=explode(',',$product[$i]['props']);
			$product[$i]['prop']=$prop;
		}

		$prop=json_decode($goods['props']);
		$prop_num=count($prop);
		switch($prop_num){
			case 1:
				$prop1=get_object_vars($prop[0]);
			    $prop_n[]=$prop1['prop_name'];
			break;
			case 2:
				$prop1=get_object_vars($prop[0]);
			    $prop_n[]=$prop1['prop_name'];

				$prop2=get_object_vars($prop[1]);
			    $prop_n[]=$prop2['prop_name'];
			break;
		}
		if(!empty($goods['props'])){
		    $this->prop_n=$prop_n;
		}
		$pdt=unserialize(stripslashes($goods['pdt']));
		$Pdt=M('Goods_model_value');
		for($j=0;$j<count($pdt);$j++){
			$value=$Pdt->where('id='.$pdt[$j]['pdt'])->find();
			if($value['leixing']=='b'){
				$pdt[$j]['key']=json_decode($value['value_key']);
			}
			$pdt[$j]['type']=$value['leixing'];
		}

        $this->pdt=$pdt;
		$this->prop_num=$prop_num;
		$this->goods=$goods;
		$this->product=$product;
		$this->assign("goods",$goods);
		$this->display();
	}

	//保存更新
	public function save(){
		$Goods     = M('Goods');
		$Products = M('Products');
		$Picmm=M("Goods_pic");
		$map['goods_id']=$this->_post('goods_id');
		
		//获取基本信息
		$data['cat_id']             =$this->_post('goods_cat');        //商品分类
		$data['goods_name']  =$this->_post('goods_name');     //商品名称
		$data['goods_brand']  =$this->_post('goods_brand');    //品牌
		$data['bn']                   =$this->_post('goods_bn');         //货号
		$data['unit']                 =$this->_post('goods_unit');       //单位
        $data['s_intro']            =$this->_post('s_intro');              //简介
	    $data['is_post']           =$this->_post('is_post');             //是否上架
	    $data['price']               =$this->_post('goods_price');     //价格
		$data['cost']                =$this->_post('goods_cost');      //成本
		$data['market_price']   =$this->_post('mktprice');           //市场价
		$data['weight']             =$this->_post('goods_weight');  //重量
		$data['store_place']    =$this->_post('goods_place');   //货位
		$data['intro']               =stripslashes($_POST['content']);//详细介绍
		$data['goods_label']    =$this->_post('goods_label');  //商品标签
		$data['shop_id']         = $this->_post('shop_id');
		$store                        =$this->_post('goods_store');//库存
		$main_pic                  =$this->_post('o_pic');//封面图片

		$getpic=$Picmm->where('pic_id='.$main_pic)->find();
		$data['s_pic']=$getpic['s_pic'];
		$data['m_pic']=$getpic['m_pic'];


		$data['last_motify']    =time();

		//获取规格差别价格
		$prop_price=$this->_post('prop_price');
		$prop_store=$this->_post('prop_store');

		//获取扩展属性
		$kz_name =   $this->_post('kz_name');   //获取扩展属性名 @数组 与扩展值对应，注意：如果扩展值为空则丢弃
		$kuozhan  =   $this->_post('kuozhan');   //获取扩展属性值  @数组
		$kuozhan_id  =   $this->_post('value_id');   //获取扩展属性值  @数组
		for($i=0;$i<count($kuozhan);$i++){
			if(!empty($kuozhan[$i])){
				$goods_kz[]=array('pdt'=>$kuozhan_id[$i],'kz_name'=>$kz_name[$i],'kuozhan'=>$kuozhan[$i]); //%处理得到数据库数据
			}
		}
				
        //获取规格名
		$prop_name     =$this->_post('prop_name');  //获取规格名    @数组
		$prop1     =    $this->_post('prop1');           //获取规格值1  @数组
		$prop2     =    $this->_post('prop2');           //获取规格值2  @数组
		$product_id  =  $this->_post('product_id');

		//如果基本信息库存没有输入，则将差别库存加总
		if(empty($store)){
			$sto=0;
			for($i=0;$i<count($prop1);$i++){
				$sto+=$prop_store[$i];
			}
			$data['store']=$sto;
		}else{
			$data['store']=$store;    //库存
		}
        
		//过滤相同的规格值
		foreach($prop1 as $v1){if(!in_array($v1,$n_prop1)&&!empty($v1)) $n_prop1[]=$v1;}
		foreach($prop2 as $v2){if(!in_array($v2,$n_prop2)&&!empty($v2)) $n_prop2[]=$v2;}
		//将所有的规格转为数组，存入e_goods:props字段
		$prop_num=count($prop_name);
		switch($prop_num){
			case 1:$prop[]=array('prop_name'=>$prop_name[0],'prop_value'=>$n_prop1);break;
			case 2:$prop[]=array('prop_name'=>$prop_name[0],'prop_value'=>$n_prop1);
			            $prop[]=array('prop_name'=>$prop_name[1],'prop_value'=>$n_prop2);break;
		}
		//%处理得到数据库数据
		if(!empty($prop1)){
			$data['props']=json_encode($prop);
		}else{
			$data['props']='';
		}
		$data['pdt']=serialize($goods_kz);//扩展属性

		//@开始更新goods
		$good_id=$Goods->where($map)->save($data);
		//@更新products
		for($i=0;$i<count($prop1);$i++){
			$data2['price']=$prop_price[$i];
			$data2['store']=$prop_store[$i];
			$data2['last_modify']=time();
			if(empty($prop2)){
					$data2['props']=$prop1[$i];
				}else{
					$data2['props']=$prop1[$i].",".$prop2[$i];
			}

			if(empty($product_id[$i])){
				//为空则插入
				$data2['goods_id']=$this->_post('goods_id');
				$data2['uptime']=time();
				$data2['bn']=$this->_post('goods_bn'); 
				$data2['cost']=$this->_post('goods_cost');
				$data2['market_price']=$this->_post('mktprice');  
				$data2['name']=$this->_post('goods_name'); 
				$data2['weight']=$this->_post('goods_weight');
                $Products->add($data2);
			}else{
				//不为空则更新
				$Products->where('product_id='.$product_id[$i])->save($data2);
			}
			
		}//for -end
		//@更新图片
		$pic=R("Goodspic/upload");    
		for($j=0;$j<count($pic);$j++){
			$data3['goods_id']=$this->_post('goods_id');
			$data3['s_pic']=$pic[$j]['savepath']."s_".$pic[$j]['savename'];
			$data3['m_pic']=$pic[$j]['savepath']."m_".$pic[$j]['savename'];
			$data3['b_pic']=$pic[$j]['savepath']."b_".$pic[$j]['savename'];
			$Picmm->add($data3);
		}
		//pic -end
		//异常修复
		//已有规格全部删除后对product进行空值补充
		$isnull=$Products->where($map)->select();
		if(false==$isnull){
			$data4['goods_id']=$this->_post('goods_id');
			$data4['uptime']=time();
			$data4['last_modify']=time();
			$data4['bn']=$this->_post('goods_bn'); 
			$data4['price']=$this->_post('goods_price');
			$data4['cost']=$this->_post('goods_cost');
			$data4['market_price']=$this->_post('mktprice'); 
			$data4['store']=$data['store']; 
			$data4['name']=$this->_post('goods_name'); 
			$data4['weight']=$this->_post('goods_weight');
			$data4['props']='';
			$Products->add($data4);
		}else{
			$map2['goods_id']=$this->_post('goods_id');
			$map2['props']='';
			$Products->where($map2)->delete();
		}
		$this->success("修改成功");
	}

	//商品删除
	public function remove(){
		$goods_id=$this->_get('id');
		$this->del_goods($goods_id);
		//垃圾回收
		R('Garbage/goods_collect');
		echo "<a href='javascript:;' onclick='history.go(-1);'>>>返回</a>";
	}

	public function del_goods($goods_id){
		$Goods=M('Goods');
		$Products=M('Products');
		$Pic=M('Goods_pic');
		$good=$Goods->where('goods_id='.$goods_id)->find();

		//查找、删除内容图片
		echo "开始删除内容图片：<br>";
		preg_match_all("/<img.*?src=\".*?\/uploads\/img\/(.*?)\/(.*?)\" \/>/",$good['intro'],$con_pic);
		for($i=0;$i<count($con_pic[2]);$i++){
			$map['intro']=array('like','%'.$con_pic[2][$i].'%');
			$map['goods_id']=array('neq',$goods_id);
			//检查图片是否被其他商品使用
			$ck_intrio=$Goods->where($map)->select();
			if(false==$ck_intrio){
				$file="./uploads/img/".$con_pic[1][$i]."/".$con_pic[2][$i];
			    $dir="./uploads/img/".$con_pic[1][$i]."/";
				if(unlink($file)){echo $con_pic[2][$i]."……删除成功<br>";}else{echo $con_pic[1][$i]."/".$con_pic[2][$i]."……删除失败或者文件不存在<br>";}
				//删除空目录
				rmdir($dir);
			}
		}
		//查找、删除缩略图
		echo "开始删除缩略图：<br>";
		$pics=$Pic->where('goods_id='.$goods_id)->select();
		preg_match_all("/.\/uploads\/(.*?)\/.*?/",$pics[$j]['s_pic'],$pic_con);
		for($j=0;$j<count($pics);$j++){
			if((unlink($pics[$j]['s_pic']))&&(unlink($pics[$j]['m_pic']))&&(unlink($pics[$j]['b_pic']))){
				$Pic->where('pic_id='.$pics[$j]['pic_id'])->delete();
				rmdir('./uploads/'.$pic_con[1].'/');
				echo "……缩略图删除成功<br>";
			}else{
				if((!file_exists($pics[$j]['s_pic']))&&(!file_exists($pics[$j]['m_pic']))&&(!file_exists($pics[$j]['b_pic']))){
					$Pic->where('pic_id='.$pics[$j]['pic_id'])->delete();
					echo "……缩略图删除成功<br>";
				}else{
				    echo "……缩略图删除失败或文件不存在<br>";
				}
			}
			
		}
		//删除记录
		$del_pro=$Products->where('goods_id='.$goods_id)->delete();
		if($del_pro){
			$result=$Goods->where('goods_id='.$goods_id)->delete();
			if($result){echo $good['name']."……删除成功";}
		}else{
			echo $good['name']."……删除失败";
		}
	}
	/*del_goods -end*/

	//获取商品列表(后台显示商品列表使用ajaxlist.html)
	public function goods_list(){
		$Goods=M('Goods');
		$Cat=M('Goods_cat');

		import("@.ORG.Page");
		$cat=$this->_get('cat');
		$post=$this->_get('post');
		$bn=$this->_get('id');
		$name=urldecode($this->_get('name'));
		
		if(!empty($cat)){
			$map['e_goods_cat.path']=array('like','%,'.$cat.'%');
		}
		if($post!=''){$map['e_goods.is_post']=$post;	}
		if(!empty($bn)){$map['goods_id|bn']=$bn;}
		if(!empty($name)){$map['goods_name']=array('like','%'.$name.'%');}

		$goods=$Goods->join('e_goods_cat ON e_goods.cat_id=e_goods_cat.cat_id')->order('e_goods.goods_id DESC')->where($map)->select();

		$param = array(
			'result'=>$goods,			//分页用的数组或sql
			'listvar'=>'goods',			//分页循环变量
			'listRows'=>10,			//每页记录数
			'parameter'=>'cat='.$cat.'&post='.$post,//url分页后继续带的参数
			'target'=>'content',	//ajax更新内容的容器id，不带#
			'pagesId'=>'page',		//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'=>'Goods:ajaxlist',//ajax更新模板
		);
		$this->page($param);
		$this->display();
	}

	public function page($param) {
		extract($param);
		import("@.ORG.Page");
		//总记录数
		$flag = is_string($result);
		$listvar = $listvar ? $listvar : 'goods';
		$listRows = $listRows? $listRows : 21;
		if ($flag)
			$totalRows = M()->table($result . ' a')->count();
		else
			$totalRows = ($result) ? count($result) : 1;
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}

	//删除规格产品
	public function del_product(){
		$Pro=M('Products');
		$map['product_id']=$this->_post('pro_id');
		$re=$Pro->where($map)->delete();
		if($re){echo "1";}
	}


}

?>